// 文件校验
function checkFiles(files) {
  let fileNum = files.length;
  let errors = [];
  let canUpload = true;
  // 是否文件为空
  if (fileNum == 0) {
    // 用户未选择文件，不必提示错误
    canUpload = false;
  } else if (fileNum > 1) {
    // 安卓端可以选择多张照片，那就先放开吧
    // errors.push(
    //   Funcs.GetTerms(
    //     'Schema.UserDefine.PageMDRAdd.仅限单文件上传',
    //     '仅限单文件上传',
    //   ),
    // );
    // canUpload = false;
  } else {
    const file = files[0];
    const maxSizeByM = 20;

    // 仅限excel
    if (
      ![
        '.jpg',
        '.png',
        '.jpeg',
        '.bmp',
        '.svg',
        '.webp',
        '.tif',
        '.tiff',
        '.ico',
      ].some(v => file.name.endsWith(v))
    ) {
      errors.push(
        Funcs.GetTerms(
          'Schema.Controls.fasr_editor.Terms.onlyImage',
          '上传失败，只允许上传图片！',
        ),
      );
      canUpload = false;
    }

    // 超出大小
    if (file.size > maxSizeByM * 1024 * 1024) {
      errors.push(
        Funcs.GetTerms(
          'Schema.Controls.fasr_editor.Terms.imgNotExceeded',
          '图片大小不能超过',
        ) + ` ${maxSizeByM} M`,
      );
      canUpload = false;
    }
  }

  return { errors, canUpload };
}

// 解析excel为json数据
function cookFile(file, callFn) {
  console.log('=========== cookFile', file);
  const reader = new FileReader();
  reader.onload = function (e) {
    // console.log(e.target.result);
    callFn(e.target.result);
  };
  reader.readAsDataURL(file);
}

// 创建input节点 上传图片用
function createInputForUploadImage(isCamera = false) {
  const $uploadInput = document.createElement('input');

  $uploadInput.setAttribute('type', 'file');
  $uploadInput.setAttribute(
    'style',
    'width:0 !important; height:0 !important;visibility: hidden !important; opacity:0;',
  );
  $uploadInput.setAttribute('accept', 'image/*');
  $uploadInput.setAttribute('multiple', 'multiple');
  if (isCamera) $uploadInput.setAttribute('capture', 'camera');

  return $uploadInput;
}

export default class UploadImgEntities {
  body = document.documentElement;
  $uploadInput = null;

  init(callFn, isCamera = false) {
    if (!this.$uploadInput) {
      const $uploadInput = createInputForUploadImage(isCamera);

      $uploadInput.addEventListener('change', e => {
        const files = e.target.files;
        console.log('====== change', files);
        const { errors, canUpload } = checkFiles(files);
        if (!canUpload) return Funcs.Notify(caption, message, type);
        [...files].forEach(file => {
          cookFile(file, callFn);
        });
      });

      this.$uploadInput = $uploadInput;
    }

    this.append();
  }

  append() {
    this.body.appendChild(this.$uploadInput);
  }

  destory() {
    this.body.removeChild(this.$uploadInput);
  }

  open() {
    this.$uploadInput.click();
  }
}
